package cn.tedu.gateway.ip;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Set;

@Component
public class RedisIpFilter implements GlobalFilter, Ordered {
    @Autowired
    RedisIpListService redisIpListService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求中的ip地址
        String clientIp = exchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
        //2.检查黑名单
        Set<String> blackList = redisIpListService.getBlackList();
        if (blackList.contains(clientIp)) {
            exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
            return exchange.getResponse().setComplete();
        }
        //3.白名单
        Set<String> whiteList = redisIpListService.getWhiteList();
        if (!whiteList.isEmpty() && !whiteList.contains(clientIp)) {
            exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
            return exchange.getResponse().setComplete();
        }
        //4.允许请求继续处理
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
